<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('富文本编辑demo')"/>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="/tinymce/js/tinymce/tinymce.min.js"></script>
    <script src="/tinymce/zh_CN.js"></script>
    <style>
        .tox-statusbar__branding {
            display: none;
        }
        .note-header {
            margin: 20px 0;
        }

        .note-title {
            width: 100%;
            padding: 10px;
            font-size: 18px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        .note-actions {
            margin: 10px 0;
        }

        .note-actions button {
            margin-right: 10px;
            padding: 8px 16px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .note-actions button:hover {
            background: #40a9ff;
        }

        .note-list {
            margin-top: 20px;
            border-top: 1px solid #eee;
            padding-top: 20px;
        }

        .note-item {
            padding: 10px;
            border: 1px solid #eee;
            margin-bottom: 10px;
            cursor: pointer;
        }

        .note-item:hover {
            background: #f5f5f5;
        }
    </style>
</head>

<body>
<h1>我的笔记</h1>

<!-- 笔记列表 -->
<div class="note-list">
    <h3>笔记列表</h3>
    <div id="noteListContainer"></div>
</div>

<!-- 操作按钮 -->
<div class="note-actions">
    <button onclick="saveNote()">保存笔记</button>
    <button onclick="newNote()">新建笔记</button>
    <button onclick="loadNoteList()">刷新列表</button>
</div>

<!-- 笔记标题输入 -->
<div class="note-header">
    <input type="text" id="noteTitle" class="note-title" placeholder="请输入笔记标题...">
</div>


<!-- 富文本编辑器 -->
<form method="post">
    <textarea id="mytextarea">开始记录你的想法...</textarea>
</form>

<th:block th:include="include :: footer"/>
<script>
    let currentNoteId = ''; // 当前编辑的笔记ID

    tinymce.init({
        selector: '#mytextarea',
        language: 'zh_CN',
        plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave autoresize',
        toolbar: 'mycustombutton code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight formatpainter axupimgs',
        height: 500,
        min_height: 400,
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',

        // 图片上传处理 - 使用base64格式
        images_upload_handler: function (blobInfo, success, failure) {
            const reader = new FileReader();

            reader.onload = function (e) {
                const base64 = e.target.result.split(',')[1];
                const fileName = blobInfo.filename();
                const fileType = blobInfo.blob().type;

                // 调用base64上传函数
                uploadImageToServer(base64, fileName, fileType, function (imageUrl) {
                    success(imageUrl);
                }, function (error) {
                    failure('上传失败: ' + error);
                });
            };

            reader.onerror = function () {
                failure('图片读取失败');
            };

            // 读取blob为base64
            reader.readAsDataURL(blobInfo.blob());
        },

        // 自定义文件选择器（保持不变）
        file_picker_callback: function (callback, value, meta) {
            if (meta.filetype === 'image') {
                $('<input>', {
                    type: 'file',
                    accept: 'image/*',
                    css: {
                        display: 'none',
                        width: '200px',
                        height: '40px',
                        fontSize: '16px'
                    }
                })
                    .appendTo('body')
                    .on('change', function () {
                        const file = this.files[0];
                        const reader = new FileReader();

                        reader.onload = function (e) {
                            const base64 = e.target.result.split(',')[1];
                            uploadImageToServer(base64, file.name, file.type, function (imageUrl) {
                                callback(imageUrl, {alt: file.name});
                            });
                        };
                        reader.readAsDataURL(file);

                        $(this).remove();
                    })
                    .trigger('click');
            }
        },

        setup: editor => {
            // 初始化编辑器
            editor.on('init', function () {
                loadNoteList(); // 加载笔记列表
            });

            // 自定义上传图片按钮
            editor.ui.registry.addButton('mycustombutton', {
                text: '上传本地图片',
                onAction: () => {
                    const input = document.createElement('input');
                    input.type = 'file';
                    input.accept = 'image/*';
                    input.onchange = e => {
                        const file = e.target.files[0];
                        if (file) {
                            const reader = new FileReader();
                            reader.onload = e => {
                                const base64 = e.target.result.split(',')[1];
                                uploadImageToServer(base64, file.name, file.type, function (imageUrl) {
                                    // 插入图片到编辑器
                                    editor.insertContent(`<img src="${imageUrl}" alt="${file.name}" />`);
                                });
                            };
                            reader.readAsDataURL(file);
                        }
                    };
                    input.click();
                }
            });
        }
    });

    // 保存笔记
    function saveNote() {
        const textTitle = $("#noteTitle").val().trim();
        const textContent = tinymce.activeEditor.getContent();

        if (!textTitle) {
            alert('请输入笔记标题');
            return;
        }

        if (!textContent) {
            alert('笔记内容不能为空');
            return;
        }

        const noteData = {
            textTitle: textTitle,
            textContent: textContent
        };

        fetch('/sys/textArea/save', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(noteData)
        })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('保存成功');
                    currentNoteId = result.data; // 更新当前笔记ID
                    loadNoteList(); // 刷新列表
                } else {
                    alert('保存失败: ' + result.msg);
                }
            })
            .catch(error => {
                console.error('保存失败:', error);
                alert('保存失败，请重试');
            });
    }

    // 新建笔记
    function newNote() {
        currentNoteId = '';
        $("#noteTitle").val('');
        tinymce.activeEditor.setContent('');
    }

    // 加载笔记列表
    function loadNoteList() {
        fetch('/sys/textArea/list')
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    displayNoteList(result.data);
                } else {
                    console.error('加载列表失败:', result.msg);
                }
            })
            .catch(error => {
                console.error('加载列表失败:', error);
            });
    }

    // 显示笔记列表
    function displayNoteList(notes) {
        const container = $("#noteListContainer");
        if (notes.length === 0) {
            container.html('<p>暂无笔记</p>');
            return;
        }

        const html = notes.map(note => `
        <div class="note-item" onclick="loadNote('${note.id}')">
            <strong>${note.textTitle}</strong>
            <div style="color: #666; font-size: 12px; margin-top: 5px;">
                ${new Date(note.updateTime).toLocaleString()}
            </div>
        </div>
    `).join('');
        container.html(html);
    }

    // 加载单个笔记
    function loadNote(noteId) {
        $.ajax({
            url: `/sys/textArea/get/${noteId}`,
            type: 'GET',
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    const note = result.data;
                    currentNoteId = note.id;
                    $('#noteTitle').val(note.textTitle);
                    tinymce.activeEditor.setContent(note.textContent);
                } else {
                    alert('加载笔记失败: ' + result.msg);
                }
            },
            error: function(xhr, status, error) {
                console.error('加载笔记失败:', error);
                alert('加载笔记失败');
            }
        });
    }

    // 上传图片到服务器
    function uploadImageToServer(base64, fileName, fileType, callback) {
        const requestData = {
            fileContent: base64,
            fileName: fileName,
            fileType: fileType
        };

        $.ajax({
            url: '/sys/image/save',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(requestData),
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    const imageUrl = '/sys/image/show/' + result.data;
                    callback(imageUrl);
                } else {
                    alert('图片上传失败');
                }
            },
            error: function(xhr, status, error) {
                console.error('上传失败:', error);
                alert('图片上传失败');
            }
        });
    }

    // 页面加载完成后初始化
   /* $(document).ready(function() {
        loadNoteList();
    });*/
</script>
</body>
</html>